package com.example.musicplayer.fragment;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.musicplayer.R;
import com.example.musicplayer.activity.BaseActivity;
import com.example.musicplayer.commonUtils.DrawUtil;
import com.example.musicplayer.commonUtils.StringUtil;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.dialogTools.ImageDisplayDialog;
import com.example.musicplayer.musicTools.MusicPlayMode;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.view.MusicVisualizerView;
import com.example.musicplayer.viewTools.ViewRotateAnimation;

public class MusicPlayTab2Fragment extends BaseFragment implements View.OnClickListener {
    private static final int PERMISSION_RECORD_AUDIO = 1;
    private static final int DISPLAY_VISUALIZER = 0;
    private static final int ADJUST_BASS_BOOST = 1;
    private static final int ADJUST_VIRTUAL = 2;
    private static final int ADJUST_REVERB = 3;
    private int mAdjustMode = DISPLAY_VISUALIZER;
    private MusicVisualizerView mVisualizerView;
    private ImageView mImageViewBig;
    private TextView mTextViewCurrent;
    private Button mEnableButton;
    private Button mCloseButton;
    private SeekBar mSeekBar;
    //设置回调监听对象
    private CallBackListener mCallBackListener;
    private MusicService.MusicBinder mMusicBinder;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music_play_tab2, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        addListener();
        setEnableTimer(true, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mMusicBinder = mCallBackListener.getMusicBinder();
        updateView();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        pauseTimer();
        if (mMusicBinder != null) {
            mMusicBinder.enableVisualizer(false, null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_RECORD_AUDIO) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && mMusicBinder != null) {
                openVisualizer(true, true);
            }
        }
    }

    @Override
    protected boolean onRefreshView() {
        int current = mMusicBinder.getCurrent();
        mSeekBar.setProgress(current);
        mTextViewCurrent.setText(StringUtil.getMusicFormatTime(current));
        return true;
    }

    private void initView() {
        FragmentActivity fa = getActivity();
        if (fa != null) {
            mVisualizerView = fa.findViewById(R.id.visualizer);
            mImageViewBig = fa.findViewById(R.id.imageview_music_play_tab2_big);
            mTextViewCurrent = fa.findViewById(R.id.textview_music_play_tab2_current);
            mEnableButton = fa.findViewById(R.id.enable);
            mCloseButton = fa.findViewById(R.id.close);
            mSeekBar = fa.findViewById(R.id.seekbar_music_play);
        }
    }

    //更新这个fragment的界面
    private void updateView() {
        updateChangingMusic();
        MusicPlayMode initPlayMode = MusicPlayMode.RANDOM;
        if (mMusicBinder != null) {
            initPlayMode = mMusicBinder.getMode();
        }
        updateModeChanged(initPlayMode, false);
        //setup visualizer
        if (MusicPlayerSettings.isDisplayVisualizer() && checkRecordAudioPermission()) {
            openVisualizer(true, false);
        }
    }

    //切换歌曲时更新信息
    private void updateChangingMusic() {
        if (mMusicBinder != null) {
            Bitmap bitmap = mMusicBinder.getAlbumBitmap();
            if (bitmap != null) {
                Bitmap bitmap1 = DrawUtil.copyBitmap(bitmap);
                mCallBackListener.setBackground(bitmap1);
                mImageViewBig.setImageBitmap(bitmap);
                mVisualizerView.setColor(DrawUtil.getMainColorOfPicture(bitmap, DrawUtil.LIGHT_MUTED));
            }
            if (getActivity() != null) {
                ((TextView) getActivity().findViewById(R.id.textview_music_play_tab2_title)).setText(mMusicBinder.getTitle());
                ((TextView) getActivity().findViewById(R.id.textview_music_play_tab2_artist)).setText(mMusicBinder.getArtist());
                ((TextView) getActivity().findViewById(R.id.textview_music_play_tab2_duration))
                        .setText(StringUtil.getMusicFormatTime(mMusicBinder.getDuration()));
            }
            mTextViewCurrent.setText(StringUtil.getMusicFormatTime(mMusicBinder.getCurrent()));
            mSeekBar.setMax(mMusicBinder.getDuration());
            mSeekBar.setProgress(mMusicBinder.getCurrent());
            changeMusicFavorite(mMusicBinder.getMusicFavorite() == 1);
            changeMusicState(mMusicBinder.isPlaying());
        }
    }

    private void addListener() {
        mVisualizerView.setOnClickListener(this);
        mImageViewBig.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (getContext() != null) {
                    ImageDisplayDialog dialog = new ImageDisplayDialog(getContext());
                    dialog.setImage(mMusicBinder.getId());
                    dialog.show();
                }
                return false;
            }
        });
        mImageViewBig.setOnClickListener(this);
        if (getActivity() != null) {
            getActivity().findViewById(R.id.bass_boost).setOnClickListener(this);
            getActivity().findViewById(R.id.virtual).setOnClickListener(this);
            getActivity().findViewById(R.id.reverb).setOnClickListener(this);
            getActivity().findViewById(R.id.sound_effect_settings).setOnClickListener(this);
            getActivity().findViewById(R.id.textview_music_play_tab2_title).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_favorite).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_sing).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_tune).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_download).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_comment).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_more).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_change).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_last).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_next).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_play).setOnClickListener(this);
            getActivity().findViewById(R.id.imageview_music_play_tab2_list).setOnClickListener(this);
            getActivity().findViewById(R.id.textview_music_play_tab2_lyric).setOnClickListener(this);
        }
        mEnableButton.setOnClickListener(this);
        mCloseButton.setOnClickListener(this);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mTextViewCurrent.setText(StringUtil.getMusicFormatTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                pauseTimer();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mMusicBinder.seekTo(mSeekBar.getProgress());
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bass_boost:
                if (getActivity() != null && mAdjustMode != ADJUST_BASS_BOOST) {
                    mAdjustMode = ADJUST_BASS_BOOST;
                    getActivity().findViewById(R.id.sound_effect_visualizer).setVisibility(View.GONE);
                    getActivity().findViewById(R.id.sound_effect_settings).setVisibility(View.VISIBLE);
                    setupSoundEffectSettingsView();
                }
                break;
            case R.id.virtual:
                if (getActivity() != null && mAdjustMode != ADJUST_VIRTUAL) {
                    mAdjustMode = ADJUST_VIRTUAL;
                    getActivity().findViewById(R.id.sound_effect_visualizer).setVisibility(View.GONE);
                    getActivity().findViewById(R.id.sound_effect_settings).setVisibility(View.VISIBLE);
                    setupSoundEffectSettingsView();
                }
                break;
            case R.id.reverb:
                if (getActivity() != null && mAdjustMode != ADJUST_REVERB) {
                    mAdjustMode = ADJUST_REVERB;
                    getActivity().findViewById(R.id.sound_effect_visualizer).setVisibility(View.GONE);
                    getActivity().findViewById(R.id.sound_effect_settings).setVisibility(View.VISIBLE);
                    setupSoundEffectSettingsView();
                }
                break;
            case R.id.sound_effect_settings:
                mAdjustMode = DISPLAY_VISUALIZER;
                if (getActivity() != null) {
                    getActivity().findViewById(R.id.sound_effect_visualizer).setVisibility(View.VISIBLE);
                    getActivity().findViewById(R.id.sound_effect_settings).setVisibility(View.GONE);
                }
                break;
            case R.id.visualizer:
            case R.id.imageview_music_play_tab2_big:
                doClickPicture();
                break;
            case R.id.textview_music_play_tab2_title:
                if (getActivity() instanceof BaseActivity) {
                    ((BaseActivity) getActivity()).jumpToMusicDetailsActivity();
                }
                break;
            case R.id.imageview_music_play_tab2_favorite:
                doClickFavorite();
                break;
            case R.id.imageview_music_play_tab2_sing:
                doClickSing();
                break;
            case R.id.imageview_music_play_tab2_tune:
                doClickTune();
                break;
            case R.id.imageview_music_play_tab2_download:
                doClickDownload();
                break;
            case R.id.imageview_music_play_tab2_comment:
                doClickComment();
                break;
            case R.id.imageview_music_play_tab2_more:
                doClickMore();
                break;
            case R.id.imageview_music_play_tab2_change:
                doClickChange();
                break;
            case R.id.imageview_music_play_tab2_last:
                doClickLast();
                break;
            case R.id.imageview_music_play_tab2_play:
                doClickPlay();
                break;
            case R.id.imageview_music_play_tab2_next:
                doClickNext();
                break;
            case R.id.imageview_music_play_tab2_list:
                doClickList();
                break;
            case R.id.textview_music_play_tab2_lyric:
                doClickLyric();
                break;
            case R.id.enable:
                if (mMusicBinder != null) {
                    if (mAdjustMode == ADJUST_BASS_BOOST) {
                        mMusicBinder.enableBassBoost(true);
                    } else if (mAdjustMode == ADJUST_VIRTUAL) {
                        mMusicBinder.enableVirtual(true);
                    } else if (mAdjustMode == ADJUST_REVERB) {
                        mMusicBinder.enableReverb(true);
                    }
                }
                mEnableButton.setEnabled(false);
                mCloseButton.setEnabled(true);
                if (getActivity() != null) {
                    getActivity().findViewById(R.id.seekbar_area).setVisibility(View.VISIBLE);
                }
                ToastUtil.makeToast(getString(R.string.toast_enable));
                break;
            case R.id.close:
                if (mMusicBinder != null) {
                    if (mAdjustMode == ADJUST_BASS_BOOST) {
                        mMusicBinder.enableBassBoost(false);
                    } else if (mAdjustMode == ADJUST_VIRTUAL) {
                        mMusicBinder.enableVirtual(false);
                    } else if (mAdjustMode == ADJUST_REVERB) {
                        mMusicBinder.enableReverb(false);
                    }
                }
                mEnableButton.setEnabled(true);
                mCloseButton.setEnabled(false);
                if (getActivity() != null) {
                    getActivity().findViewById(R.id.seekbar_area).setVisibility(View.GONE);
                }
                ToastUtil.makeToast(getString(R.string.toast_close));
                break;
            default:
                break;
        }
    }

    private void doClickLyric() {
        mCallBackListener.switchFragment(2);
    }

    //点击触发展示歌曲列表
    private void doClickList() {
        mCallBackListener.showMusicListDialog();
    }

    private void doClickNext() {
        mMusicBinder.startNext();
        updateChangingMusic();
    }

    private void doClickPlay() {
        if (mMusicBinder != null) {
            mMusicBinder.changePlayingState();
        }
    }

    private void doClickLast() {
        mMusicBinder.startLast();
        updateChangingMusic();
    }

    //改变播放模式
    private void doClickChange() {
        mMusicBinder.changeMode();
    }

    private void doClickMore() {
    }

    private void doClickComment() {
    }

    private void doClickDownload() {
    }

    private void doClickTune() {
    }

    private void doClickSing() {
    }

    //点击喜爱图片时调用
    private void doClickFavorite() {
        mMusicBinder.changeMusicFavorite();
    }

    private void doClickPicture() {
        if (checkRecordAudioPermission() && mMusicBinder != null) {
            openVisualizer(!MusicPlayerSettings.isDisplayVisualizer(), true);
        }
    }

    private void openVisualizer(final boolean open, boolean enableAnimation) {
        if (getActivity() == null) {
            return;
        }
        if (enableAnimation) {
            View displayView = getActivity().findViewById(R.id.display_area);
            ViewRotateAnimation animation = new ViewRotateAnimation(displayView, ViewRotateAnimation.ROTATION_Y
                    , open ? 0f : 180f, open ? 180f : 360f);
            animation.setPivotX(displayView.getWidth() / 2);
            animation.setPivotY(displayView.getHeight() / 2);
            animation.setDuration(500);
            animation.setUpdateListener(new ViewRotateAnimation.UpdateListener() {
                @Override
                public void onUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    if (getActivity() != null) {
                        if (open && value >= 90f) {
                            getActivity().findViewById(R.id.sound_effect_view).setVisibility(View.VISIBLE);
                            getActivity().findViewById(R.id.cardview_big_image).setVisibility(View.GONE);
                        }
                        if (!open && value >= 270f) {
                            getActivity().findViewById(R.id.sound_effect_view).setVisibility(View.GONE);
                            getActivity().findViewById(R.id.cardview_big_image).setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
            animation.start();
        } else {
            if (open) {
                getActivity().findViewById(R.id.display_area).setRotationY(180f);
            }
            getActivity().findViewById(R.id.sound_effect_view).setVisibility(open ? View.VISIBLE : View.GONE);
            getActivity().findViewById(R.id.cardview_big_image).setVisibility(open ? View.GONE : View.VISIBLE);
        }
        MusicPlayerSettings.setDisplayVisualizer(open);
        if (open) {
            if (mMusicBinder != null) {
                mMusicBinder.enableVisualizer(true, new MusicService.VisualizerListener() {
                    @Override
                    public void captureWaveFormData(byte[] waveform) {
                        mVisualizerView.update(waveform);
                    }
                });
            }
        } else {
            if (mMusicBinder != null) {
                mMusicBinder.enableVisualizer(false, null);
            }
        }
    }

    private boolean checkRecordAudioPermission() {
        if (getActivity() == null) {
            return false;
        }
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}
                    , PERMISSION_RECORD_AUDIO);
            return false;
        }
        return true;
    }

    private void setupSoundEffectSettingsView() {
        if (getActivity() == null) {
            return;
        }
        final TextView seekBarText = getActivity().findViewById(R.id.seekbar_text);
        SeekBar soundEffectSeekBar = getActivity().findViewById(R.id.settings_seekbar);
        String text = "/1000";
        switch (mAdjustMode) {
            case ADJUST_VIRTUAL:
                ((TextView) getActivity().findViewById(R.id.settings_title)).setText(R.string.virtual_adjust);
                mEnableButton.setEnabled(!MusicPlayerSettings.isEnableVirtual());
                mCloseButton.setEnabled(MusicPlayerSettings.isEnableVirtual());
                getActivity().findViewById(R.id.seekbar_area).setVisibility(MusicPlayerSettings.isEnableVirtual() ?
                        View.VISIBLE : View.GONE);
                text = MusicPlayerSettings.getVirtualStrength() + text;
                soundEffectSeekBar.setMax(1000);
                soundEffectSeekBar.setProgress(MusicPlayerSettings.getVirtualStrength());
                break;
            case ADJUST_REVERB:
                ((TextView) getActivity().findViewById(R.id.settings_title)).setText(R.string.reverb_adjust);
                mEnableButton.setEnabled(!MusicPlayerSettings.isEnableReverb());
                mCloseButton.setEnabled(MusicPlayerSettings.isEnableReverb());
                getActivity().findViewById(R.id.seekbar_area).setVisibility(MusicPlayerSettings.isEnableReverb() ?
                        View.VISIBLE : View.GONE);
                text = (MusicPlayerSettings.getReverbLevel() + 9000) + "/11000";
                soundEffectSeekBar.setMax(11000);
                soundEffectSeekBar.setProgress(MusicPlayerSettings.getReverbLevel() + 9000);
                break;
            case ADJUST_BASS_BOOST:
            default:
                ((TextView) getActivity().findViewById(R.id.settings_title)).setText(R.string.bass_boost_adjust);
                mEnableButton.setEnabled(!MusicPlayerSettings.isEnableBassBoost());
                mCloseButton.setEnabled(MusicPlayerSettings.isEnableBassBoost());
                getActivity().findViewById(R.id.seekbar_area).setVisibility(MusicPlayerSettings.isEnableBassBoost() ?
                        View.VISIBLE : View.GONE);
                text = MusicPlayerSettings.getBassBoostStrength() + text;
                soundEffectSeekBar.setMax(1000);
                soundEffectSeekBar.setProgress(MusicPlayerSettings.getBassBoostStrength());
                break;
        }
        seekBarText.setText(text);
        soundEffectSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    String text;
                    if (mAdjustMode == ADJUST_REVERB) {
                        text = progress + "/11000";
                    } else {
                        text = progress + "/1000";
                    }
                    seekBarText.setText(text);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mMusicBinder != null) {
                    if (mAdjustMode == ADJUST_BASS_BOOST) {
                        mMusicBinder.setBassBoostStrength(seekBar.getProgress());
                    } else if (mAdjustMode == ADJUST_VIRTUAL) {
                        mMusicBinder.setVirtualStrength(seekBar.getProgress());
                    } else if (mAdjustMode == ADJUST_REVERB) {
                        mMusicBinder.setReverbLevel(seekBar.getProgress() - 9000);
                    }
                }
            }
        });
    }

    //播放模式改变时调用
    public void updateModeChanged(MusicPlayMode mode, boolean showToast) {
        if (getActivity() != null) {
            String text = "已切换到";
            ImageView modeView = getActivity().findViewById(R.id.imageview_music_play_tab2_change);
            switch (mode) {
                case RANDOM:
                    modeView.setImageResource(R.drawable.activity_music_play_tab2_random);
                    text += "随机播放";
                    break;
                case REPEAT:
                    modeView.setImageResource(R.drawable.activity_music_play_tab2_repeat);
                    text += "顺序播放";
                    break;
                case REPEAT_ONE:
                    modeView.setImageResource(R.drawable.activity_music_play_tab2_repeat_one);
                    text += "单曲循环";
                    break;
            }
            if (showToast) {
                new ToastUtil(getContext(), text).shortShow().setGravity(Gravity.CENTER, 0, 300)
                        .setAlpha(0.7f).show();
            }
        }
    }

    public void updateMusicPrepared() {
        updateChangingMusic();
    }

    public void changeMusicState(boolean isPlaying) {
        if (getActivity() != null) {
            ImageView playView = getActivity().findViewById(R.id.imageview_music_play_tab2_play);
            if (isPlaying) {
                playView.setImageResource(R.drawable.activity_music_play_tab2_start);
                startTimer();
            } else {
                playView.setImageResource(R.drawable.activity_music_play_tab2_pause);
                pauseTimer();
            }
        }
    }

    //改变音乐喜爱的属性
    public void changeMusicFavorite(boolean isFavorite) {
        if (getActivity() != null) {
            ((ImageView) getActivity().findViewById(R.id.imageview_music_play_tab2_favorite)).
                    setImageResource(isFavorite ? R.drawable.activity_music_play_tab2_favorite :
                            R.drawable.activity_music_play_tab2_not_favorite);
        }
    }

    //改变音乐正在播放的歌词
    public void changeMusicLyric(String lyric) {
        if (getActivity() != null) {
            ((TextView) getActivity().findViewById(R.id.textview_music_play_tab2_lyric)).setText(lyric);
        }
    }

    public void setOnCallBackListener(CallBackListener callBackListener) {
        mCallBackListener = callBackListener;
    }

    //声明回调接口
    public interface CallBackListener {
        public MusicService.MusicBinder getMusicBinder();

        public void setBackground(Bitmap bitmap);

        public void showMusicListDialog();

        //切换这个activity的fragment页面
        public void switchFragment(int position);
    }
}